/**
 * 
 */
package de.guidoludwig.af;

import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;

import com.jgoodies.binding.list.SelectionInList;

/**
 * @author guido
 *
 */
public class TableFactory {

	private TableFactory() {
		//
	}
	
	public static JComponent createTable(final SelectionInList<?> sil,
			TableModel tableModel) {
		final JTable t = new JTable(tableModel);
		t.getSelectionModel().setSelectionMode(
				ListSelectionModel.SINGLE_SELECTION);
		t.getSelectionModel().addListSelectionListener(
				new ListSelectionListener() {
					@Override
					public void valueChanged(ListSelectionEvent e) {
						int selection = t.getSelectionModel()
								.getMinSelectionIndex();
						if (selection == -1) {
							sil.setSelection(null);
						} else {
							sil.setSelectionIndex(selection);
						}
					}
				});
		if (sil.hasSelection()) {
			t.getSelectionModel().setSelectionInterval(sil.getSelectionIndex(),
					sil.getSelectionIndex());
		}
		return new JScrollPane(t);
	}

}

